package leetcode.剑指offer.后40;

import org.junit.Test;

/**
 * @author :songyaozhang
 * @date :Created 2021/8/2 10:01
 * @description :
 */
public class 剑指_65_不用加减乘除做加法 {
    @Test
    public void test() {
        Solution solution = new Solution();
        System.out.println(solution.add(10, -5));
    }


    //进位 + 非进位
    /*
     a                      20  0001 0100
     b                      17  0001 0001
    进位((a & b) << 1)           0010 0000
    非进位(a ^ b)                0000 0101
    和                           0010 0101
     */
    class Solution {
        public int add(int a, int b) {
            while (b != 0) {
                //进位
                int c = (a & b) << 1;
                //非进位
                a ^= b;
                b = c;
            }
            return a;
        }
    }
}
